import { Injectable, UnauthorizedException } from '@nestjs/common'
import { JwtService } from '@nestjs/jwt'
import { AdminService } from 'src/modules/admin/admin.service'
import { LoginStaffDto } from 'src/modules/staff/dto/staff.dto'
import { Staff } from 'src/modules/staff/entities/staff.entity'
import { StaffService } from 'src/modules/staff/staff.service'

@Injectable()
export class AuthService {
  constructor(
    private readonly staffService: StaffService,
    private readonly adminService: AdminService,
    private readonly jwtService: JwtService
  ) {}

  async login(loginStaff: LoginStaffDto) {
    const user = await this.staffService.login(loginStaff)
    if (!user) {
      return null
    }
    const admin = await this.adminService.findOne(user.id)
    const payload = { username: user.name, sub: user.id }
    return {
      id: user.id,
      access_token: this.jwtService.sign(payload),
      isAdmin: admin ? true : false
    }
  }
  async validatePayload(payload: any) {
    const { sub: userId } = payload
    const user = await this.staffService.findOne(userId)
    if (!user) {
      return null
    }
    const admin = await this.adminService.findOne(userId)
    return {
      id: user.id,
      name: user.name,
      role: admin ? admin.role.id : 3
    }
  }
}
